<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件浏览器</title>
    <link rel="stylesheet" href="https://unpkg.com/layui@2.11.5/dist/css/layui.css">
    <style>
        .container {
            padding: 20px;
        }
        .path-input {
            margin-bottom: 15px;
        }
        .file-info {
            margin-bottom: 15px;
        }
        .status-bar {
            margin-top: 10px;
            padding: 10px;
            background-color: #f8f8f8;
            border-radius: 4px;
        }
        
        /* 文件图标样式 */
        .file-icon {
            display: inline-block;
            width: 16px;
            height: 16px;
            margin-right: 8px;
            vertical-align: middle;
        }
        
        .file-icon.folder {
            color: #ffa03a;
        }
        
        .file-icon.file {
            color: #1890ff;
        }
        
        .file-name-cell {
            display: flex;
            align-items: center;
        }
        
        /* 文件类型标签样式 */
        .type-tag {
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 12px;
            color: white;
        }
        
        .type-tag.folder {
            background-color: #ffa03a;
        }
        
        .type-tag.file {
            background-color: #1890ff;
        }
        
        /* 权限显示样式 */
        .permissions {
            font-family: 'Courier New', monospace;
            font-size: 13px;
            background-color: #f0f0f0;
            padding: 2px 4px;
            border-radius: 2px;
        }
        
        /* 文件大小对齐 */
        .file-size {
            text-align: right;
        }
        
        /* 右键菜单样式 */
        .context-menu {
            position: fixed;
            background: white;
            border: 1px solid #d2d2d2;
            border-radius: 6px;
            padding: 1px 0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
            z-index: 9999;
            min-width: 110px;
            display: none;
            cursor: pointer;
        }
        
        .context-menu-item {
            padding: 2px 8px;
            cursor: pointer;
            font-size: 14px;
            color: #333;
            display: flex;
            align-items: center;
        }
        
        .context-menu-item:hover {
            background-color: #f0f0f0;
        }
        
        .context-menu-item i {
            margin-right: 8px;
            width: 20px;
        }
        
        .context-menu-separator {
            height: 1px;
            background-color: #e6e6e6;
            margin: 4px 0;
        }

        .status-info { margin: 10px 0; padding: 10px; background-color: #f0f9ff; border-left: 4px solid #1e90ff; }
        .error-info { margin: 10px 0; padding: 10px; background-color: #fff5f5; border-left: 4px solid #f56565; color: #e53e3e; }
        .loading { text-align: center; padding: 20px; color: #666; }
    </style>
</head>
<body>
    <div class="container">
        <!-- 连接信息表单 -->
        <div class="layui-card">
            <div class="layui-card-header">远程主机连接</div>
            <div class="layui-card-body">
                <div class="layui-form layui-form-pane">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">主机名</label>
                            <div class="layui-input-inline">
                                <input type="text" id="hostName" placeholder="如: server1" value="云主机" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">IP地址</label>
                            <div class="layui-input-inline">
                                <input type="text" id="hostIP" placeholder="192.168.1.100" value="10.21.162.157" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">端口</label>
                            <div class="layui-input-inline" style="width: 80px;">
                                <input type="number" id="hostPort" value="22" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">用户名</label>
                            <div class="layui-input-inline">
                                <input type="text" id="username" placeholder="root" value="root" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">密码</label>
                            <div class="layui-input-inline">
                                <input type="password" id="password" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline" style="width: 1100px;">
                            <label class="layui-form-label">目录路径</label>
                            <div class="layui-input-inline">
                                <input type="text" id="pathInput" class="layui-input" placeholder="请输入目录路径，例如: /home/user 或 C:\Users" value="/" style="width: 900px;">
                                <!-- <input type="text" id="remotePath" value="/home/mm" placeholder="/home/user" class="layui-input" style="width: 900px;"> -->
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <button type="button" id="connectBtn" class="layui-btn">测试连接</button>
                        <button type="button" class="layui-btn" id="loadBtn">
                            <i class="layui-icon layui-icon-search"></i> 加载
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 状态显示 -->
        <div id="statusInfo" class="status-info" style="display: none;">
            <span id="statusText"></span>
        </div>
        <div id="errorInfo" class="error-info" style="display: none;">
            <span id="errorText"></span>
        </div>


        <div class="layui-card">
            <div class="layui-card-body">

                <!-- 文件信息显示区域 -->
                <div class="file-info">
                    <div id="currentPath" class="layui-text layui-font-14" style="margin-bottom: 10px;"></div>
                    <table class="layui-hide" id="fileTable" lay-filter="fileTable"></table>
                </div>

                <!-- 状态栏 -->
                <div class="status-bar">
                    <span id="operateShow">准备就绪</span>
                    <span id="fileCount" style="float: right;"></span>
                </div>

                <!-- 消息显示区域 -->
                <div id="messageArea"></div>
            </div>
        </div>
    </div>

    <!-- 右键菜单 -->
    <div id="contextMenu" class="context-menu">
        <div class="context-menu-item" data-action="open">
            <i class="layui-icon layui-icon-ok-circle"></i>
            打开
        </div>
        <div class="context-menu-separator"></div>
        <div class="context-menu-item" data-action="rename">
            <i class="layui-icon layui-icon-edit"></i>
            重命名
        </div>
        <div class="context-menu-item" data-action="copy">
            <i class="layui-icon layui-icon-file"></i>
            复制
        </div>
        <div class="context-menu-item" data-action="move">
            <i class="layui-icon layui-icon-export"></i>
            移动
        </div>
        <div class="context-menu-item" data-action="paste">
            <i class="layui-icon layui-icon-list"></i>
            粘贴
        </div>
        <div class="context-menu-separator"></div>
        <div class="context-menu-item" data-action="delete">
            <i class="layui-icon layui-icon-delete"></i>
            删除
        </div>
        <div class="context-menu-separator"></div>
        <div class="context-menu-item" data-action="permissions">
            <i class="layui-icon layui-icon-set"></i>
            修改权限
        </div>
    </div>

    <script src="https://unpkg.com/layui@2.11.5/dist/layui.js"></script>
    <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
    <script>
        layui.use(['table', 'layer'], function(){
            const table = layui.table;
            const layer = layui.layer;
            
            // 连接Socket.IO
            const socket = io();
            let currentPath = '/';
            let selectedRowData = null;


            function getConfig() {
                return {
                    name: document.getElementById('hostName').value,
                    host: document.getElementById('hostIP').value,
                    port: document.getElementById('hostPort').value,
                    username: document.getElementById('username').value,
                    password: document.getElementById('password').value,
                    path: document.getElementById('pathInput').value
                };
            }

            function validateConfig() {
                const config = getConfig();
                if (!config.name || !config.host || !config.port || !config.username || !config.password || !config.path) {
                    layer.msg('请填写完整连接信息', {icon: 2});
                    return false;
                }
                return true;
            }

            function showStatus(message) {
                statusText.textContent = message;
                statusInfo.style.display = 'block';
                errorInfo.style.display = 'none';
            }
            
            function showError(message) {
                errorText.textContent = message;
                errorInfo.style.display = 'block';
                statusInfo.style.display = 'none';
            }
            
            // Socket连接事件
            socket.on('connect', function() {
                showStatus('已连接到服务器');
            });

            socket.on('disconnect', function() {
                showError('与服务器断开连接');
            });

            socket.on('connection_result', function(data) {
                console.log('收到连接结果:', data);
                if (data.success) {
                    showStatus(data.msg);
                } else {
                    showError(data.msg);
                }
            });

            socket.on('event_result', function(data) {
                // loading.style.display = 'none';
                if (data.success) {
                    if (data.cmd_event == 'detail') {
                        console.log(data.data);
                        showStatus(data.msg);
                        table.reload('fileTable', {
                            data: data.data[0].content
                        });
                        updateOperateStatus(`成功加载 ${data.data[0].content.length} 个项目`, 'success');
    
                    } 
                } else {
                    showError(data.msg);
                }
            });


            // 连接远程主机
            connectBtn.addEventListener('click', function() {
                if (!validateConfig()) {
                    return;
                }
                console.log("连接远程主机"+getConfig())
                showStatus('正在连接远程主机...');
                // connectBtn.disabled = true;
                socket.emit('login_remote', getConfig());
            });


            document.getElementById('loadBtn').addEventListener('click', function() {
                // const path = document.getElementById('pathInput').value.trim();
                // if (path) loadDirectory(path);
                loadDirectory();
            });

            document.getElementById('pathInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') document.getElementById('loadBtn').click();
            });

            
            function loadDirectory() {
                updateOperateStatus('正在加载目录信息...', 'loading');
                showStatus('正在加载目录信息...');
                // layer.load(1, {shade: [0.1, '#fff']});
                // socket.emit('get_directory_info', {path: path});
                path = getConfig().path;
                host_key = getConfig().name+"|"+getConfig().host+":"+getConfig().port+"|"+getConfig().username;
                let config = {
                      cmd_event:"detail",
                      params:[path] ,
                      hosts_key: [host_key]
                }
                socket.emit('command_event', config);
            }


            // 自定义渲染函数
            function renderFileName(d) {
                const iconClass = d.type === '目录' ? 'layui-icon-folder' : 'layui-icon-file';
                const iconColor = d.type === '目录' ? 'folder' : 'file';
                return `
                    <div class="file-name-cell">
                        <i class="layui-icon ${iconClass} file-icon ${iconColor}" style="vertical-align: middle; horizontal-align:middle"></i>

                        <span>${d.name}</span>
                    </div>
                `;
            }

            function renderFileType(d) {
                const tagClass = d.type === '目录' ? 'folder' : 'file';
                return `<span class="type-tag ${tagClass}">${d.type}</span>`;
            }

            function renderPermissions(d) {
                return `<span class="permissions">${d.permissions}</span>`;
            }

            function renderFileSize(d) {
                return `<span class="file-size">${d.size}</span>`;
            }

            function renderToolbar() {
                return `
                    <div class="layui-btn-container">
                        <button class="layui-btn layui-btn-sm" lay-event="refresh">
                            <i class="layui-icon layui-icon-refresh"></i> 刷新
                        </button>
                        <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="parentDir">
                            <i class="layui-icon layui-icon-up"></i> 上级目录
                        </button>
                        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="getSelected">
                            <i class="layui-icon layui-icon-ok"></i> 获取选中项
                        </button>
                        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="createFolder">
                            <i class="layui-icon layui-icon-folder"></i> 新建文件夹
                        </button>
                        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="createFile">
                            <i class="layui-icon layui-icon-file"></i> 新建文件
                        </button>
                    </div>
                `;
            }

            // 右键菜单处理
            const contextMenu = document.getElementById('contextMenu');

            // 显示右键菜单
            function showContextMenu(x, y, rowData) {
                selectedRowData = rowData;
                
                // 调整菜单文本
                const openItem = contextMenu.querySelector('[data-action="open"]');
                openItem.innerHTML = `<i class="layui-icon layui-icon-ok-circle"></i>${rowData.type === '目录' ? '进入目录' : '打开文件'}`;
                
                // 显示菜单
                contextMenu.style.left = x + 'px';
                // 如果处于底部，调整位置
                if (y + contextMenu.offsetHeight > window.innerHeight) {
                    y = window.innerHeight - contextMenu.offsetHeight;
                }
                contextMenu.style.top = y + 'px';
                contextMenu.style.display = 'block';
            }

            // 隐藏右键菜单
            function hideContextMenu() {
                contextMenu.style.display = 'none';
            }

            // 处理右键菜单动作
            function handleContextMenuAction(action) {
                if (!selectedRowData) return;
                
                const fileData = selectedRowData;
                
                switch(action) {
                    case 'open':
                        if (fileData.type === '目录') {
                            let newPath;
                            if (currentPath.endsWith('/') || currentPath.endsWith('\\')) {
                                newPath = currentPath + fileData.name;
                            } else {
                                const separator = currentPath.includes('\\') ? '\\' : '/';
                                newPath = currentPath + separator + fileData.name;
                            }
                            document.getElementById('pathInput').value = newPath;
                            loadDirectory(newPath);
                        } else {
                            layer.msg(`打开文件: ${fileData.name}`, {icon: 1});
                            // TODO: 发送打开文件请求到后端
                        }
                        break;
                    case 'rename':
                        layer.prompt({
                            title: '重命名',
                            value: fileData.name,
                            maxlength: 255
                        }, function(newName, index) {
                            layer.msg(`重命名 "${fileData.name}" 为 "${newName}"`, {icon: 1});
                            layer.close(index);
                            // TODO: 发送重命名请求到后端
                        });
                        break;
                    case 'copy':
                        layer.msg(`复制文件: ${fileData.name}`, {icon: 1});
                        updateOperateStatus(`复制文件: ${fileData.name} >> `, 'loading');
                        // TODO: 发送复制请求到后端
                        break;
                    case 'move':
                        layer.msg(`移动文件: ${fileData.name}`, {icon: 1});
                        // TODO: 发送移动请求到后端
                        break;
                    case 'paste':
                        layer.msg(`粘贴文件: ${fileData.name}`, {icon: 1});
                        updateOperateStatus(`粘贴文件: ${fileData.name} >> `, 'loading');
                        // TODO: 发送粘贴请求到后端
                        break;
                    case 'delete':
                        layer.confirm(`确定要删除 "${fileData.name}" 吗？`, {
                            icon: 3,
                            title: '确认删除'
                        }, function(index) {
                            layer.msg(`删除文件: ${fileData.name}`, {icon: 1});
                            layer.close(index);
                            // TODO: 发送删除请求到后端
                        });
                        break;
                    case 'permissions':
                        layer.alert(`
                            <div style="text-align: left;">
                                <p><strong>当前权限:</strong> ${fileData.permissions}</p>
                                <p><strong>所有者:</strong> ${fileData.owner}</p>
                                <p><strong>用户组:</strong> ${fileData.group}</p>
                                <br>
                                <p style="color: #999;">权限修改功能待实现...</p>
                            </div>
                        `, {
                            title: '修改权限 - ' + fileData.name,
                            area: ['400px', '250px']
                        });
                        // TODO: 发送修改权限请求到后端
                        break;
                }
            }

            // 初始化表格
            const tableInstance = table.render({
                elem: '#fileTable',
                cols: [[
                    {type: 'radio', fixed: 'left', width: 50},
                    {field: 'type', title: '类型', width: 80,sort: true, templet: function(d) { return renderFileType(d); }, unresize: true},
                    {field: 'name', title: '文件名', width: 250,sort: true, templet: function(d) { return renderFileName(d); }},
                    {field: 'size', title: '大小', width: 120, sort: true, templet: function(d) { return renderFileSize(d); }},
                    {field: 'size_bytes', title: '字节数', width: 120, sort: true},
                    {field: 'modified_time', title: '修改时间', width: 180, sort: true},
                    {field: 'permissions', title: '权限', width: 120, templet: function(d) { return renderPermissions(d); }},
                    {field: 'owner', title: '所有者', width: 100, sort: true},
                    {field: 'group', title: '用户组', width: 100, sort: true}
                ]],
                data: [],
                skin: 'grid',
                even: true,
                page: false,
                loading: true,
                toolbar: renderToolbar(),
                defaultToolbar: ['filter'],
                height: 500,
                initSort: {
                    field: 'name',
                    type: 'asc'
                },
                done: function() {
                    // 表格渲染完成后绑定右键事件
                    setTimeout(() => {
                        const tableBody = document.querySelector('#fileTable + .layui-table-view .layui-table-body tbody');
                        if (tableBody) {
                            tableBody.addEventListener('contextmenu', function(e) {
                                e.preventDefault();
                                
                                const tr = e.target.closest('tr[data-index]');
                                if (tr) {
                                    const index = parseInt(tr.getAttribute('data-index'));
                                    const tableData = table.cache['fileTable'];
                                    const rowData = tableData[index];
                                    
                                    if (rowData) {
                                        // 选中该行
                                        table.setRowChecked('fileTable', {
                                            index: index,
                                            type: 'radio'
                                        });
                                        
                                        showContextMenu(e.clientX, e.clientY, rowData);
                                    }
                                }
                            });
                        }
                    }, 100);
                }
            });

            // 点击其他地方隐藏菜单
            document.addEventListener('click', function(e) {
                if (!contextMenu.contains(e.target)) {
                    hideContextMenu();
                }
            });

            // 右键菜单项点击事件
            contextMenu.addEventListener('click', function(e) {
                e.stopPropagation();
                const menuItem = e.target.closest('.context-menu-item');
                if (menuItem) {
                    const action = menuItem.dataset.action;
                    handleContextMenuAction(action);
                    hideContextMenu();
                }
            });

            // // 接收目录数据
            // socket.on('directory_data', function(data) {
            //     console.log('收到目录数据:', data);
            //     currentPath = data.path;
                
            //     document.getElementById('currentPath').innerHTML = 
            //         `<strong>当前路径:</strong> <code>${data.path}</code>`;
                
            //     table.reload('fileTable', {
            //         data: data.files
            //     });
                
            //     updateOperateStatus(`成功加载 ${data.count} 个项目`, 'success');
            //     const folderCount = data.files.filter(f => f.type === '目录').length;
            //     const fileCount = data.files.filter(f => f.type === '文件').length;
            //     document.getElementById('fileCount').textContent = 
            //         `共 ${data.count} 个项目 (${folderCount} 个目录, ${fileCount} 个文件)`;
                
            //     layer.closeAll('loading');
            // });

            // socket.on('directory_error', function(data) {
            //     updateOperateStatus(`错误: ${data.error}`, 'error');
            //     layer.closeAll('loading');
            //     layer.msg(data.error, {icon: 2, time: 3000});
            // });

            // 表格行单击事件
            table.on('row(fileTable)', function(obj){
                var data = obj.data;
                selectedRowData = data;
                layer.msg(`选中: ${data.name} (${data.type})`, {offset: '65px', time: 2000});
                obj.setRowChecked({type: 'radio'});
            });

            // 表格行双击事件
            table.on('rowDouble(fileTable)', function(obj){
                var data = obj.data;
                if (data.type === '目录') {
                    let newPath;
                    if (currentPath.endsWith('/') || currentPath.endsWith('\\')) {
                        newPath = currentPath + data.name;
                    } else {
                        const separator = currentPath.includes('\\') ? '\\' : '/';
                        newPath = currentPath + separator + data.name;
                    }
                    document.getElementById('pathInput').value = document.getElementById('pathInput').value + '/'+newPath;
                    loadDirectory(newPath);
                } else {
                    // 处理文件双击事件
                    // TODO: 实现文件打开功能
                    layer.msg(`双击打开文件: ${data.name}`, {offset: '65px', time: 2000});
                }
            });

            // 头工具栏事件
            table.on('toolbar(fileTable)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id);
                switch(obj.event){
                    case 'refresh':
                        loadDirectory(currentPath);
                        break;
                    case 'getSelected':
                        var data = checkStatus.data;
                        if (data.length === 0) {
                            layer.msg('请先选择一行数据', {icon: 0});
                        } else {
                            const fileInfo = data[0];
                            layer.alert(`
                                <div style="text-align: left;">
                                    <p><strong>文件名:</strong> ${fileInfo.name}</p>
                                    <p><strong>类型:</strong> ${fileInfo.type}</p>
                                    <p><strong>大小:</strong> ${fileInfo.size}</p>
                                    <p><strong>修改时间:</strong> ${fileInfo.modified_time}</p>
                                    <p><strong>权限:</strong> ${fileInfo.permissions}</p>
                                    <p><strong>所有者:</strong> ${fileInfo.owner}</p>
                                    <p><strong>用户组:</strong> ${fileInfo.group}</p>
                                </div>
                            `, {
                                title: '文件详细信息',
                                area: ['400px', '300px']
                            });
                        }
                        break;
                    case 'parentDir':
                        let pathParts = currentPath.includes('\\') ? currentPath.split('\\') : currentPath.split('/');
                        let separator = currentPath.includes('\\') ? '\\' : '/';
                        
                        if (pathParts.length > 1) {
                            pathParts.pop();
                            let parentPath = pathParts.join(separator);
                            if (separator === '/' && parentPath === '') parentPath = '/';
                            if (separator === '\\' && parentPath.length === 2 && parentPath.endsWith(':')) parentPath += '\\';
                            
                            if (parentPath !== currentPath) {
                                document.getElementById('pathInput').value = parentPath;
                                loadDirectory(parentPath);
                            }
                        }
                        break;              
                    case 'createFolder':
                        createFolder();
                        break;
                    case 'createFile':
                        createFile();
                        break;
                    }
            });


            function updateOperateStatus(message, type = 'info') {
                const operateShow = document.getElementById('operateShow');
                operateShow.textContent = message;
                operateShow.style.color = type === 'success' ? '#4caf50' : type === 'error' ? '#ff5722' : type === 'loading' ? '#1890ff' : '#666';
            }

            // setTimeout(() => document.getElementById('loadBtn').click(), 500);
        });
    </script>
</body>
</html>